package com.czy.service.impl;

import com.czy.mapper.DeptMapper;
import com.czy.mapper.EmpMapper;
import com.czy.myexception.CustomException;
import com.czy.pojo.Dept;
import com.czy.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    @Override
    public List<Dept> findAll() {
        return deptMapper.findAll();
    }

    @Override
    public void deleteById(Integer id) {
        //获取部门的人数
        Integer count = empMapper.getCount(id);
        //部门下关联的有员工，是不允许删除的
        if (count != null && count > 0) {
            //存在抛出异常
            throw new CustomException(405, "部门下有员工，不能直接删除 ~ ");
        }

        //不存在，正常删除
        deptMapper.deleteById(id);
    }

    @Override
    public void addDept(Dept dept) {
        //补全基础属性createTime和updateTime
        //新创建的部门信息，创建和修改时间是一样的
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());

        deptMapper.addDept(dept);
    }

    @Override
    public Dept findById(Integer id) {
        return deptMapper.findById(id);
    }

    @Override
    public void updateById(Dept dept) {
        //补全基础属性 - updateTime
        //修改名称后，修改时间也要进行改变
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.updateById(dept);
    }


}
